package core

import (
	"errors"
	"github.com/blang/semver/v4"
)

type DetailRes struct {
	Code int      `json:"code"`
	Data []Detail `json:"data"`
}

func (d DetailRes) LatestManifest() Manifest {
	lenD := len(d.Data)
	if lenD <= 0 {
		panic("bundle is not exist in the repo")
	}
	latestManifest := d.Data[0]
	v, _ := semver.Make(latestManifest.Version)
	for i := 1; i < lenD; i++ {
		if lv, _ := semver.Make(d.Data[i].Version); v.LT(lv) {
			latestManifest = d.Data[i]
		}
	}
	manifest := FromDetailManifest(latestManifest)
	return manifest
}

func (d DetailRes) Match(version string) (m Manifest, err error) {
	lenD := len(d.Data)
	if lenD <= 0 {
		err = errors.New("bundle is not exist in the remote repository")
		return
	}
	matchedManifest := d.Data[0]
	v, _ := semver.Make(matchedManifest.Version)
	for i := 1; i < lenD; i++ {
		if version == d.Data[i].Version {
			matchedManifest = d.Data[i]
			break
		} else if lv, _ := semver.Make(d.Data[i].Version); v.LT(lv) {
			matchedManifest = d.Data[i]
		}
	}
	m = FromDetailManifest(matchedManifest)
	return
}
